package com.hontech.kaltaapp.serial.usb

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import com.hontech.kaltaapp.app.AppContext
import com.hontech.kaltaapp.utils.log
import kotlinx.coroutines.CompletableDeferred

private const val ACTION_USB_PERMISSION = "USB.PERMISSION"

suspend fun openUsb(usb: UsbManager, device: UsbDevice): UsbDeviceConnection {
    val ret = usb.hasPermission(device)
    if (!ret) {
        requestPermission(usb, device)
    }
    log("开始打开usb")
    return usb.openDevice(device)
}

private suspend fun requestPermission(usb: UsbManager, device: UsbDevice) {
    val usbReceiver = UsbPermissionReceiver()
    val filter = IntentFilter(ACTION_USB_PERMISSION)

    AppContext.registerReceiver(usbReceiver, filter)


    val intent = Intent(ACTION_USB_PERMISSION)
    intent.setPackage(AppContext.packageName)
    val pi = PendingIntent.getBroadcast(AppContext, 0, intent, PendingIntent.FLAG_MUTABLE)


    usb.requestPermission(device, pi)
    val ret = usbReceiver.promise.await()
    AppContext.unregisterReceiver(usbReceiver)
    if (!ret) {
        throw IllegalStateException("用户拒绝USB授权")
    }
}

private class UsbPermissionReceiver() : BroadcastReceiver() {

    val promise = CompletableDeferred<Boolean>()

    override fun onReceive(context: Context?, intent: Intent?) {
        log("usb 广播")
        if (intent == null) {
            return
        }
        val flag = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
        promise.complete(flag)
    }
}
